package com.yayako.main.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件读写工具类
 *
 * @author cyy
 */
public class FileUtil {
    private FileUtil() {}

    public static List<String> readFileByLine(String path) {
        File file = new File(path);
        if (!file.isFile() || !file.exists()) {
            System.err.println("该文件不存在，请检查输入路径是否正确。");
            return null;
        }
        System.out.println("源文件读取中，请稍等。。。");
        BufferedReader reader = null;
        List<String> list = new ArrayList<>();
        String tmp;
        try {
            reader = new BufferedReader(new FileReader(file));
            while ((tmp = reader.readLine()) != null) {
                if ((tmp = tmp.trim()).length() > 0) {
                    list.add(tmp);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    /**
     * 将输出写入指定txt，覆盖
     *
     * @param path txt路径
     * @param content 输出内容
     */
    public static void write2Txt(String path, String content) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(path);
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void clearTXT(String path) {
        write2Txt(path, "");
    }

    /**
     * 将输出写入指定txt
     *
     * @param path txt路径
     * @param content 输出内容
     * @param splice 是否拼接
     */
    public static void write2Txt(String path, String content, boolean splice) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(path, splice);
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
